package com.sfjswl.fp.core.relation;

import com.sfjswl.fp.common.enums.NodeRunStateEnum;
import com.sfjswl.fp.core.base.BaseNode;
import com.sfjswl.fp.core.base.BaseRelation;
import com.sfjswl.fp.core.context.RuleContext;
import com.sfjswl.fp.core.utils.RuleLinkedList;

public final class Any extends BaseRelation {

  @Override
  protected NodeRunStateEnum processNode(RuleContext ctx) {
    RuleLinkedList<BaseNode> children = this.getChildren();
    if (children == null || children.isEmpty()) {
      return NodeRunStateEnum.NONE;
    }
    boolean hasFalse = false;
    for (RuleLinkedList.Node<BaseNode> listNode = children.getLeft(); listNode != null; listNode = listNode.next) {
      BaseNode node = listNode.item;
      if (node != null) {
        NodeRunStateEnum stateEnum = node.process(ctx);
        if (stateEnum == NodeRunStateEnum.TRUE) {
          return NodeRunStateEnum.TRUE;
        }
        if (!hasFalse) {
          hasFalse = stateEnum == NodeRunStateEnum.FALSE;
        }
      }
    }

    if (hasFalse) {
      return NodeRunStateEnum.FALSE;
    }
    return NodeRunStateEnum.NONE;
  }
}
